import { useState, useEffect, useCallback } from "react";
import io from "socket.io-client";
import { useRecoilState } from "recoil";
import { socketState } from "@/store";
import { BACKEND_PATH } from "@/env.ts";

function useSocket() {
  const [socket, setSocket] = useRecoilState(socketState);

  useEffect(() => {
    if (!socket) {
      const newSocket = io(`${BACKEND_PATH}/ws`, {
        transports: ["websocket"],
        path: "/ws/socket.io", // 通常WebSocket的路径是 /socket.io
      });

      newSocket.on("connect", () => {
        setSocket(newSocket);
        console.log("ws connected ", newSocket.connected);
      });

      // return () => {
      //   newSocket.disconnect();
      // };
    }
  }, [socket]); // 将 socket 加入依赖数组

  return socket;
}

// 创建 useSocketIO Hook
const useSocketIO = (url, options = {}) => {
  const [socket, setSocket] = useState(null);

  // 创建 Socket.IO 连接
  useEffect(() => {
    const newSocket = io(url, options);
    setSocket(newSocket);

    // 清理函数
    return () => {
      if (newSocket) {
        newSocket.off();
        newSocket.close();
      }
    };
  }, [url, options]);

  // 监听事件
  const on = useCallback(
    (event, callback) => {
      if (socket) {
        socket.on(event, callback);
      }
    },
    [socket],
  );

  // 移除事件监听
  const off = useCallback(
    (event, callback) => {
      if (socket) {
        socket.off(event, callback);
      }
    },
    [socket],
  );

  // 发送消息
  const emit = useCallback(
    (event, ...args) => {
      if (socket) {
        socket.emit(event, ...args);
      }
    },
    [socket],
  );

  return { socket, on, off, emit };
};

export { useSocket, useSocketIO };
